
use std::sync::mpsc::{SyncSender, Receiver};
use std::collections::HashMap;

use serde_json as json;

use game;
use net;

use super::Mapping;

///接收游戏内消息并处理
pub fn receive_from_game(receiver: &Receiver<game::message::PlayerResponse>,
                         sender: &SyncSender<net::message::Message>,
                         map: &mut Mapping){
    loop{
        let ret = receiver.try_recv();
        match ret {
            Ok(ref message) => handle_chess_response(sender, map, message),
            Err(e) => break
        }
    }
}

fn handle_chess_response(sender: &SyncSender<net::message::Message>, map: &mut Mapping, message: &game::message::PlayerResponse){
    match message {
        &game::message::PlayerResponse::MatchPlayer(black, white) =>{
            let black_rep = json!({"code": "match_success", "turn": true, "opponent": black});
            let white_rep = json!({"code": "match_success", "turn": false, "opponent": white});
            let black_channel = map.get_channel(&black).unwrap();
            sender.send(net::message::Message::new(*black_channel, black_rep.to_string()));
            let white_channel = map.get_channel(&white).unwrap();
            sender.send(net::message::Message::new(*white_channel, white_rep.to_string()));
        },
        &game::message::PlayerResponse::ChessOk(user, ref body) => {
            let channel = map.get_channel(&user).unwrap();
            sender.send(net::message::Message::new(*channel, json::to_string(body).unwrap()));
        },
        &game::message::PlayerResponse::GameOver(user, ref body) => {
            let channel = map.get_channel(&user).unwrap();
            sender.send(net::message::Message::new(*channel, body.to_string()));
        },
        &game::message::PlayerResponse::Error(user, ref body) => {
            let channel = map.get_channel(&user).unwrap();
            sender.send(net::message::Message::new(*channel, body.to_string()));
        }
    }
}